package com.siashan.toolkit.api.security.plugin;

import cn.hutool.core.util.StrUtil;
import com.siashan.toolkit.api.security.exception.RestCryptoException;
import com.siashan.toolkit.api.security.properties.RestCryptoProperties;
import com.siashan.toolkit.api.security.util.sign.SignUtil;
import org.springframework.beans.factory.annotation.Autowired;

/**
 * 默认时间戳校验插件
 *
 * @author siashan
 * @since v1.0.1
 **/
public class DefaultTimeStampVerifyPlugin implements TimeStampVerifyPlugin {

    /**
     * 时间戳位数
     */
    private static int TIMESTAMP_LEN = 10;


    @Autowired
    private RestCryptoProperties restCryptoProperties;


    /**
     * 校验时间戳
     *
     * @param timeStampStr  时间戳
     * @return 是否校验通过
     */
    @Override
    public boolean verify(String timeStampStr) {
        // 当前系统时间戳
        long currentTimestamp = SignUtil.getCurrentTimestamp();
        if (StrUtil.isEmpty(timeStampStr.trim())) {
            throw new RestCryptoException("时间戳字段缺失");
        }
        // 时间戳精确到秒(10位)
        if (timeStampStr.length() != TIMESTAMP_LEN) {
            throw new RestCryptoException("请传递10位时间戳");
        }
        // 判断时间戳格式
        try {
            long timeStamp = Long.parseLong(timeStampStr);
            long timeout = restCryptoProperties.getTimeout();
            if (currentTimestamp - timeStamp > timeout) {
                throw new RestCryptoException("请求时间间隔过长拒绝服务");
            } else {
                return true;
            }
        } catch (NumberFormatException e) {
            throw new RestCryptoException("时间戳格式错误");
        }
    }
}
